#ifndef __MY_UTIL__
#define __MY_UTIL__

#include <string>
#include <fstream>
#include <string>
#include <sys/stat.h>
#include <iostream>
#include <vector>
#include <experimental/filesystem>
#include <jsoncpp/json/json.h>
#include "libary/bundle.h"

namespace cloud
{
    namespace fs = std::experimental::filesystem;
    class FileUtil
    {
    public:
        FileUtil(const std::string &filename) : _filename(filename)
        {
        }
        // 获取文件最后一次修改的时间
        time_t LastMTime()
        {
            struct stat st;
            if (stat(_filename.c_str(), &st) < 0)
            {
                std::cout << "get file last modify time fail" << std::endl;
                return -1;
            }
            return st.st_mtime;
        }
        // 获取文件最后一次访问的时间
        time_t LastATime()
        {
            struct stat st;
            if (stat(_filename.c_str(), &st) < 0)
            {
                std::cout << "get file last access time fail" << std::endl;
                return -1;
            }
            return st.st_atime;
        }
        // 获取文件大小
        int64_t FileSize()
        {
            struct stat st;
            if (stat(_filename.c_str(), &st) < 0)
            {
                std::cout << "get  file size fail" << std::endl;
                return -1;
            }
            return st.st_size;
        }
        // 获取文件名称
        std::string FileName()
        {
            size_t pos = _filename.rfind("/");
            if (pos == std::string::npos)
            {
                return _filename;
            }
            return _filename.substr(pos + 1);
        }
        // 获取文件一段区间的内容
        bool GetPosLen(std::string *body, size_t pos, size_t len)
        {
            // 把文件内容从pos位置开始，读取len长度放到body里面
            // 判断pos 和 len是否合理
            size_t fsize = FileSize();
            if (pos + len > fsize)
            {
                std::cout << "Len is not unreasonable" << std::endl;
                return false;
            }
            std::ifstream ifs;
            ifs.open(_filename, std::ios::binary);
            if (ifs.is_open() == false)
            {
                std::cout << "read file open fail" << std::endl;
                ifs.close();
                return false;
            }
            ifs.seekg(pos, std::ios::beg);
            body->resize(len);
            ifs.read(&(*body)[0], len);
            if (ifs.good() == false)
            {
                std::cout << "read file content error" << std::endl;
                ifs.close();
                return false;
            }
            return true;
        }
        bool GetContent(std::string *body)
        {
            size_t fsize = FileSize();
            return this->GetPosLen(body, 0, fsize);
        }
        // 修改文件内容
        bool SetContent(const std::string &body)
        {
            std::ofstream ofs;
            ofs.open(_filename, std::ios::binary);
            if (ofs.is_open() == false)
            {
                std::cout << "write file open fail" << std::endl;
                ofs.close();
                return false;
            }
            ofs.write(&body[0], body.size());
            if (ofs.good() == false)
            {
                std::cout << "write file content error" << std::endl;
                ofs.close();
                return false;
            }
            ofs.close();
            return true;
        }
        bool Remove()
        {
            if(Exists() == false)
            {
                return true;
            }
            remove(_filename.c_str());
            return true;
        }
        // 文件解压缩
        bool Compress(const std::string &packname)
        {
            // 1.把要压缩的文件内容全部读取出来
            std::string body;
            if (this->GetContent(&body) == false)
            {
                std::cout << "compress read content false" << std::endl;
                return false;
            }

            // 2.压缩文件
            std::string packed = bundle::pack(bundle::LZIP, body);
            // 3.将压缩后的文件内容写到压缩包中
            FileUtil fu(packname);
            if (fu.SetContent(packed) == false)
            {
                std::cout << "compress write content false" << std::endl;
                return false;
            }
            return true;
        }
        bool UnCompress(const std::string &newfilename)
        {
            // 1.把要解压的文件内容全部读取出来
            std::string body;
            if (this->GetContent(&body) == false)
            {
                std::cout << "uncompress read content false" << std::endl;
                return false;
            }
            // 2.解压文件
            std::string unpacked = bundle::unpack(body);
            // 3.把解压后的文件内容写到新文件中
            FileUtil fu(newfilename);
            if (fu.SetContent(unpacked) == false)
            {
                std::cout << "uncompress write content false" << std::endl;
                return false;
            }
            return true;
        }
        bool Exists()
        {
            return fs::exists(_filename);
        }
        bool CreateDirectory()
        {
            if (Exists() == true)
                return true;
            return fs::create_directories(_filename);
        }
        //遍历整个目录，获取所有文件名
        bool ScanDirectory(std::vector<std::string> *array)
        {
            for (auto &p : fs::directory_iterator(_filename))
            {
                if (fs::is_directory(p) == true)
                {
                    continue;
                }
                // relative_path 带有路径的文件名(相对路径)
                array->push_back(fs::path(p).relative_path().string());
            }
            return true;
        }

    private:
        std::string _filename;
    };

    class JsonUtil
    {
    public:
        static bool Serialize(const Json::Value &root, std::string *str)
        {
            Json::StreamWriterBuilder swb;
            std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());
            std::stringstream ss;
            if (sw->write(root, &ss) != 0)
            {
                std::cout << "json write fail" << std::endl;
                return false;
            }
            *str = ss.str();
            return true;
        }
        static bool UnSerialize(const std::string &str, Json::Value *root)
        {
            Json::CharReaderBuilder crb;
            std::unique_ptr<Json::CharReader> cr(crb.newCharReader());
            std::string err;
            bool ret = cr->parse(str.c_str(), str.c_str() + str.size(), root, &err);
            if (ret == false)
            {
                std::cout << "parse error:" << err << std::endl;
                return false;
            }
            return true;
        }
    };
}

#endif
